﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace ReplayHouse
{
    class WebRequestBusiness
    {
        protected static string cookieHeader = string.Empty;
        private string statusCode = string.Empty;

        /// <summary>
        /// 回帖
        /// </summary>
        /// <param name="webRequest"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public void SendMessage(string message, string sendUrl)
        {
            sendUrl += "addnote/";

            if (string.IsNullOrEmpty(cookieHeader))
            {
                bool isLogin = Login();
                if (isLogin)
                {
                    PostWebRequest(message, sendUrl);
                }
            }
            else
            {
                PostWebRequest(message, sendUrl);
            }
        }

        ///<summary>
        /// 功能描述：模拟登录页面，提交登录数据进行登录，并记录Header中的cookie
        /// </summary>
        /// <returns>可以返回页面内容或不返回</returns>
        public bool Login()
        {
            try
            {
                string strResult = string.Empty;
                HttpWebRequest myHttpWebRequest = InitHttpWebRequest(ReplyHouseConst.LoginUrl, "POST");
                CookieContainer myCookieContainer = new CookieContainer();
                myHttpWebRequest.CookieContainer = myCookieContainer;

                Stream MyRequestStrearm = myHttpWebRequest.GetRequestStream();
                StreamWriter MyStreamWriter = new StreamWriter(MyRequestStrearm, Encoding.ASCII);
                //把数据写入HttpWebRequest的Request流
                MyStreamWriter.Write(ReplyHouseConst.Args);
                //关闭打开对象
                MyStreamWriter.Close();

                using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse())
                {
                    statusCode = response.StatusCode.ToString();
                    cookieHeader = myHttpWebRequest.CookieContainer.GetCookieHeader(new Uri(ReplyHouseConst.LoginUrl));
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312")))
                    {
                        strResult = sr.ReadToEnd();
                        if (statusCode.ToUpper().Equals("OK"))
                        {
                            return true;
                        }
                        return false;
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 功能描述：在PostLogin成功登录后记录下Headers中的cookie，然后获取此网站上其他页面的内容
        /// </summary>
        /// <param name="strURL">获取网站的某页面的地址</param>
        /// <returns>返回页面内容</returns>
        public string GetHtmlResponse(string Url, ref string statusCode)
        {
            string strResult = string.Empty;
            HttpWebRequest myHttpWebRequest = InitHttpWebRequest(Url, "GET");

            using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse())
            {
                statusCode = response.StatusCode.ToString();
                if (string.IsNullOrEmpty(cookieHeader))
                {
                    if (myHttpWebRequest.CookieContainer != null)
                    {
                        cookieHeader = myHttpWebRequest.CookieContainer.GetCookieHeader(new Uri(Url));
                    }
                }

                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    strResult = sr.ReadToEnd();
                    return strResult;
                }
            }
        }


        /// <summary>
        /// 初始化HttpWebRequest
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        private HttpWebRequest InitHttpWebRequest(string Url, string method)
        {
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
            myHttpWebRequest.AllowAutoRedirect = true;
            myHttpWebRequest.KeepAlive = true;
            myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
            myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.Method = method;

            if (!string.IsNullOrEmpty(cookieHeader))
            {
                myHttpWebRequest.Headers.Add("cookie:" + cookieHeader);
            }
            return myHttpWebRequest;
        }

        /// <summary>
        /// 提交数据
        /// </summary>
        private void PostWebRequest(string message1, string sendUrl)
        {
            string[] message = ReplyHouseConst.MessageContent;
            for (int i = message.Length - 1; i >= 0; i--)
            {
                Thread.Sleep(800);
                HttpWebRequest webRequest = InitHttpWebRequest(sendUrl, "POST");
                string postData = "content=" + message[i];
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                using (Stream newStream = webRequest.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length);    //写入参数
                    using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        {
                            string text = sr.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
}
